################################################################################
# CONGRESSIONAL INTERVENTION IN AGENCY ADJUDICATION
# AUTHORS: LINDSEY GAILMARD, DANIEL E. HO, MARK KRASS
################################################################################

################################################################################
# THIS FILE CREATES ALL FIGURES INCLUDED IN APPENDICES A-B, E-N
# APPENDIX A: DATA DESCRIPTION
# APPENDIX B: STUDY TIME PERIOD
# APPENDIX E: CLEANING DATES
# APPENDIX F: IDENTIFYING WITH MEMBERS OF CONGRESS
# APPENDIX G: MISSING DATA
# APPENDIX H: AOD CRITERIA BY INQUIRY STATUS AND AOD STATUS
# APPENDIX I: BACKGROUND ON CONGRESSIONAL INQUIRIES IN STUDY
# APPENDIX J: CONGRESSIONAL INQUIRY RATES BY DISTRICT VETERAN POPULATION
# APPENDIX K: CONGRESSIONAL INQUIRIES ON BEHALF OF UNIQUE APPELLANTS
# APPENDIX M: ROBUSTNESS
# APPENDIX N: CAUSAL MEDIATION SENSITIVITY ANALYSIS
################################################################################


# SET LOCAL WORKING DIRECTORY
setwd("/Users/lindseygailmard/Dropbox/RegLab/BVA Congressional Intervention YLJ")

getwd()

# LOAD ALL DATASETS FOR FIGURES AND TABLES
table1 <-
  read.csv("./Replication Files/Data/table1.csv", header = TRUE)
table2_fig4 <-
  read.csv("./Replication Files/Data/table2 - fig4.csv", header = TRUE)
matched_dataset <-
  read.csv("./Replication Files/Data/matched dataset.csv", header = TRUE)
inquiries <-
  read.csv("./Replication Files/Data/inquiries.csv", header = TRUE)
appeals <- 
  read.csv("./Replication Files/Data/appeals.csv", header = TRUE)

################################################################################
######################## APPENDIX A: DATA DESCRIPTION ##########################
################################################################################

# SEE "APPEALS.CSV"

################################################################################
######################## APPENDIX B: STUDY TIME PERIOD #########################
################################################################################


hist(
  appeals$nodyear,
  xlab = "Notice of Disagreement Date (Year)",
  main = "",
  ylim = c(0, 180000),
  breaks = 100
)
abline(
  v = c(2003, 2017),
  lty = 1,
  lwd = 2,
  col = "black"
)

hist(
  correspondence$corryear,
  xlab = "Correspondence Date (Year)",
  main = "",
  ylim = c(0, 96000),
  breaks = 100
)
abline(
  v = c(2003, 2017),
  lty = 1,
  lwd = 2,
  col = "black"
)

################################################################################
############### APPENDIX F: IDENTIFYING WITH MEMBERS OF CONGRESS ###############
################################################################################

inquiries <- subset(
  correspondence,
  mltype == "2" |
    mlsource == "E" | mlsource == "P" | mlsource == "X" | mlsource == "G"
)

inquiries$ml_notes_desc <- ifelse(inquiries$mlnotes == "", 1, 0)

# NUMBER OF BLANK (=1) DESCRIPTIONS
table(inquiries$ml_notes_desc)

# NUMBER OF ML NOTES THAT CONTAIN "Sen."
inquiries$senator <- ifelse(str_detect(inquiries$mlnotes, "(?i)sen"), 1, 0)
inquiries$rep <- ifelse(str_detect(inquiries$mlnotes, "(?i)cong"), 1, 0)

################################################################################
########################## APPENDIX G: MISSING DATA ############################
################################################################################

missing <- table1 %>%
  mutate(across(where(is.character), ~ na_if(., "")))

missing <- missing %>%
  mutate(saddrstt = state.x)

missing <- dplyr::select(
  missing,
  c(
    "sdob",
    "sgender",
    "sfinhard",
    "stermill",
    "shomeless",
    "sadvage",
    "saddrstt",
    "saddrzip",
    "ctyp_ps3",
    "ctyp_ps4",
    "ctyp_ps5",
    "ctyp_ps6",
    "ctyp_ps7",
    "ctyp_ps8",
    "ctyp_ps9",
    "bfso",
    "bfregoff"
  )
)

Frequency <- colSums(is.na(missing))

unique_appeals <- length(unique(table1$appeal_id))

pct_missing <- Frequency / unique_appeals
Share <- round(pct_missing, 3)

Description <- c(
  "Appellant DOB",
  "Appellant Gender",
  "Financial Hardship",
  "Terminal Illness",
  "Homeless",
  "Advanced Age",
  "Address (State)",
  "Address (Zip)",
  "WWII (9/16/40-7/25/47)",
  "Peacetime (7/26/47-6/26/50)",
  "Korean Conflict (6/27/50-1/31/55)",
  "Post-Korea (2/1/55-8/4/64)",
  "Vietnam Era (8/5/64- 5/7/75)",
  "Post-Vietnam (5/8/75-8/1/90)",
  "Persian Gulf (8/2/90-Present)",
  "Appellant Representative",
  "Regional Office"
)

table7 <- cbind(Description, Frequency, Share)

table7 <- as.data.frame(table7)

xtable(table7, type = "latex")

################################################################################
########## APPENDIX H: AOD CRITERIA BY INQUIRY STATUS AND AOD STATUS ###########
################################################################################

# SUMMARY: DOCUMENTED AOD CRITERIA BY INQURIY STATUS AND AOD STATUS
table_termill_CI <- table(table1$stermill, table1$CI)
termill_CI <- prop.table(table_termill_CI, 2)

round(termill_CI, 5)

table_termill_AOD <- table(table1$stermill, table1$aod)
termill_AOD <- prop.table(table_termill_AOD, 2)

table_finhard_CI <- table(table1$sfinhard, table1$CI)
finhard_CI <- prop.table(table_finhard_CI, 2)
table_finhard_AOD <- table(table1$sfinhard, table1$aod)
finhard_AOD <- prop.table(table_finhard_AOD, 2)

table_advage_CI <- table(table1$sadvage, table1$CI)
advage_CI <- prop.table(table_advage_CI, 2)
table_advage_AOD <- table(table1$sadvage, table1$aod)
advage_AOD <- prop.table(table_advage_AOD, 2)

table_CI <-
  rbind(termill_CI, finhard_CI, advage_CI)
table_AOD <-
  rbind(termill_AOD, finhard_AOD, advage_AOD)

table8 <- cbind(table_CI, table_AOD)

table8 <- round(table8, 3)

kbl(table8, format = "latex", booktabs = T) %>%
  add_header_above(c(
    " " = 1,
    "Inquiry Status" = 2,
    "AOD Status" = 2
  )) %>%
  kable_styling()  %>%
  column_spec(2, width = "12em") %>%
  pack_rows("Terminal Illness", 1, 3) %>%
  pack_rows("Financial Hardship", 4, 6) %>%
  pack_rows("Advanced Age", 7, 9) %>%
  save_kable("./Tables/Table 8.png")

table1$adv_age_documented <- ifelse(table1$sadvage=="Y", 1, 0)

aod_age <- table1 %>%
  group_by(nodyear) %>%
  summarise(
    adv_age_vacols = sum(adv_age_documented), 
    adv_age_manual = sum(advage)
  )

aod_age$share_documented <- aod_age$adv_age_vacols/aod_age$adv_age_manual

ggplot(data = aod_age %>% filter(nodyear<2017), aes(x = nodyear, y = share_documented)) + geom_line() +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", size = 12),
    text = element_text(size = 12),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    panel.border = element_rect(
      colour = "black",
      fill = NA,
      linewidth = 0.75
    ),
    axis.line = element_line(colour = "black")
  ) +
  ylim(0, 0.75) + xlab("NOD Year") + ylab("Fraction") +
  ggtitle("Share of Advanced Age Documented in VACOLS")

ggsave(
  "./Replication Files/Figures/Figure 16.png",
  device = "png",
  width = 5,
  height = 4
)

################################################################################
########## APPENDIX I: BACKGROUND ON CONGRESSIONAL INQUIRIES IN STUDY ##########
################################################################################

inquiries_by_year <- inquiries %>% 
  group_by(corryear) %>%
  summarise(
    inquiries = n()
  )

ggplot(data = inquiries_by_year, aes(x = corryear, y = inquiries)) + geom_line() +
  geom_point() + 
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", size = 12),
    panel.border = element_rect(
      colour = "black",
      fill = NA,
      size = 0.75
    ),
    text = element_text(size = 12),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black")
  ) +
  xlab("Correspondence Year Documented") + ylab("Congressional Intervention ") +
  ggtitle("Congressional Intervention by Year") 

ggsave(
  "./Replication Files/Figures/Figure 15.png",
  device = "png",
  width = 5,
  height = 4
)

data <- inquiries %>%
  filter(days_to_inquiry >= 0 & corrdate < as.Date("2018-01-01"))

hist(
  data$days_to_inquiry,
  xlab = "Days to Congressional Inquiry",
  main = "",
  breaks = 100
)


################################################################################
#### APPENDIX J: CONGRESSIONAL INQUIRY RATES BY DISTRICT VETERAN POPULATION ####
################################################################################

appalachian_region <- c(0102, 0103, 0104, 0105, 0106, 0107, 1303, 1307, 1308, 1309,
                        1310, 1311, 1313, 1314, 2101, 2102, 2104, 2105, 2106,
                        2406, 2801, 2802, 2803, 3619, 3621, 3623, 3705, 3706, 
                        3710, 3711, 3902, 3906, 3907, 3912, 3914, 4207, 4208, 
                        4209, 4212, 4213, 4214, 4215, 4216, 4217, 4503, 4504, 
                        4505, 4701, 4702, 4703, 4704, 4705, 4706, 5106, 5109, 
                        5401, 5402)

table2_fig4 <- table2_fig4 %>%
  mutate(
    district_CI = ifelse(is.na(district_CI), 0, district_CI),
    intervention_pct = 100 * district_CI/Veteran.Population, 
    appalachia = ifelse(cd_match %in% appalachian_region, 1, 0)
  )

# PLOT VETERAN POPULATION BY DISTRICT AGAINST CONGRESSIONAL INQUIRY RATE
fig18_a <- ggplot(
  data = table2_fig4 %>% filter(congress == 109) %>%
    mutate(Appalachia = ifelse(appalachia == TRUE, "Yes", "No")),
  aes(x = Veteran.Population, y = intervention_pct)
) +
  geom_point(aes(color = factor(Appalachia)))  +
  scale_colour_manual(values  = c("black", "dodgerblue1")) +
  labs(colour = "Appalachia") +
  geom_smooth(method = lm) +
  ggtitle("109th Congress") + ylab("Intervention Rate") +
  xlab("Veteran Population") + 
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", size = 12),
    text = element_text(size = 12),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    #panel.border = element_rect(colour="black", fill=NA, size=0.75),
    axis.line = element_line(colour = "black"),
    legend.position = "none"
  )

fig18_b <- ggplot(
  data = table2_fig4 %>% filter(congress == 110) %>%
    mutate(Appalachia = ifelse(appalachia == TRUE, "Yes", "No")),
  aes(x = Veteran.Population, y = intervention_pct)
) +
  geom_point(aes(color = factor(Appalachia)))  +
  scale_colour_manual(values  = c("black", "dodgerblue1")) +
  labs(colour = "Appalachia") +
  geom_smooth(method = lm) +
  ggtitle("110th Congress") + ylab("Intervention Rate") +
  xlab("Veteran Population") + 
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", size = 12),
    text = element_text(size = 12),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    #panel.border = element_rect(colour="black", fill=NA, size=0.75),
    axis.line = element_line(colour = "black"),
    legend.position = "none"
  )

fig18_c <- ggplot(
  data = table2_fig4 %>% filter(congress == 112) %>%
    mutate(Appalachia = ifelse(appalachia == TRUE, "Yes", "No")),
  aes(x = Veteran.Population, y = intervention_pct)
) +
  geom_point(aes(color = factor(Appalachia)))  +
  scale_colour_manual(values  = c("black", "dodgerblue1")) +
  labs(colour = "Appalachia") +
  geom_smooth(method = lm) +
  ggtitle("112th Congress") + ylab("Intervention Rate") +
  xlab("Veteran Population") + 
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", size = 12),
    text = element_text(size = 12),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    #panel.border = element_rect(colour="black", fill=NA, size=0.75),
    axis.line = element_line(colour = "black"), 
    legend.position = "none"
  )

fig18_d <- ggplot(
  data = table2_fig4 %>% filter(congress == 114) %>%
    mutate(Appalachia = ifelse(appalachia == TRUE, "Yes", "No")),
  aes(x = Veteran.Population, y = intervention_pct)
) +
  geom_point(aes(color = factor(Appalachia)))  +
  scale_colour_manual(values  = c("black", "dodgerblue1")) +
  labs(colour = "Appalachia") +
  geom_smooth(method = lm) +
  ggtitle("114th Congress") + ylab("Intervention Rate") + 
  xlab("Veteran Population") +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", size = 12),
    text = element_text(size = 12),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    #panel.border = element_rect(colour="black", fill=NA, size=0.75),
    axis.line = element_line(colour = "black"),
    legend.position = "none"
  )


fig18 <- grid.arrange(fig18_a, fig18_b, fig18_c, fig18_d, ncol = 2) 

# plot1 with legend 
fig18_a_legend <- ggplot(data = table2_fig4 %>% filter(congress == 114) %>%
                           mutate(Appalachia = ifelse(appalachia == TRUE, "Yes", "No")),
                         aes(x = Veteran.Population, y = intervention_pct)
) +
  geom_point(aes(color = factor(Appalachia)))  +
  scale_colour_manual(values  = c("black", "dodgerblue1")) +
  labs(colour = "Appalachia") + 
  theme(legend.position = "bottom") 

# function to extract legend from plot 
get_only_legend <- function(plot) { 
  plot_table <- ggplot_gtable(ggplot_build(plot)) 
  legend_plot <- which(sapply(plot_table$grobs, function(x) x$name) == "guide-box") 
  legend <- plot_table$grobs[[legend_plot]] 
  return(legend) 
} 

# extract legend from plot1 using above function 
legend <- get_only_legend(fig18_a_legend)    

# final combined plot with shared legend 
grid.arrange(fig18, legend, nrow = 2, heights = c(10, 1))

################################################################################
###### APPENDIX K: CONGRESSIONAL INQUIRIES ON BEHALF OF UNIQUE APPELLANTS ######
################################################################################

us_states <- states(cb = TRUE, resolution = "20m") %>%
  filter(NAME != "Puerto Rico") %>%
  shift_geometry()

us_states <- us_states %>%
  rename(state_fips = STATEFP)

# CONGRESSIONAL DISTRICT SHAPE FILES
# https://cdmaps.polisci.ucla.edu/

get_congress_map <- function(cong = 113) {
  tmp_file <- tempfile()
  tmp_dir  <- tempdir()
  zp <- sprintf("http://cdmaps.polisci.ucla.edu/shp/districts%03i.zip",
                cong)
  download.file(zp, tmp_file)
  unzip(zipfile = tmp_file, exdir = tmp_dir)
  fpath <- paste(tmp_dir,
                 sprintf("districtShapes/districts%03i.shp", cong),
                 sep = "/")
  st_read(fpath)
}

cd114 <- get_congress_map(114)

cd114 <- merge(cd114, fips_codes_state, by = "STATENAME")
cd114$DISTRICT <- as.numeric(cd114$DISTRICT)
cd114$cd_match <- cd114$state_fips * 100 + cd114$DISTRICT

cd114 <- cd114 %>%
  shift_geometry()

intervention_114 <- subset(table2_fig4, congress == 114)

cd114_intervention <- cd114 %>% left_join(intervention_114, by = "cd_match")
cd114_intervention$unique_appellants <- ifelse(
  is.na(cd114_intervention$unique_appellants),
  0,
  cd114_intervention$unique_appellants
)
cd114_intervention$unique_appellants_rate <- 100 * (cd114_intervention$unique_appellants /
                                                      cd114_intervention$Veteran.Population)
ggplot() +
  geom_sf(
    data = cd114_intervention,
    aes(fill = unique_appellants),
    inherit.aes = FALSE,
    alpha = 0.9,
    lwd = 0
  ) +
  geom_sf(data = us_states, alpha = 0) +
  scale_fill_distiller(palette = "Blues", direction = 1) +
  theme_void() +
  labs(fill = 'Unique Appellants') +
  theme_void() +
  theme(
    axis.title.x = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    text = element_text(family = "Times New Roman", size = 12),
    plot.caption.position = "plot",
    plot.caption = element_text(
      hjust = 0,
      family = "Times New Roman",
      size = 12
    )
  )

ggsave(
  "./Replication Files/Figures/Figure 19.png",
  device = "png",
  width = 6.5,
  height = 3
)

ggplot() +
  geom_sf(
    data = cd114_intervention,
    aes(fill = unique_appellants_rate),
    inherit.aes = FALSE,
    alpha = 0.9,
    lwd = 0
  ) +
  geom_sf(data = us_states, alpha = 0) +
  scale_fill_distiller(palette = "Blues", direction = 1) +
  theme_void() +
  labs(fill = 'Unique Appellants Rate (%)') +
  theme_void() +
  theme(
    axis.title.x = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    text = element_text(family = "Times New Roman", size = 12),
    plot.caption.position = "plot",
    plot.caption = element_text(
      hjust = 0,
      family = "Times New Roman",
      size = 12
    )
  )

ggsave(
  "./Replication Files/Figures/Figure 20.png",
  device = "png",
  width = 6.5,
  height = 3
)

################################################################################
##################### APPENDIX M: ROBUSTNESS (MATCHING) ########################
################################################################################

matched_dataset_form9 <- matched_dataset %>%
  filter(form9_pair == 1 & substantive_appeals == 1)

fig21 <- matched_dataset_form9 %>%
  filter(no_aod_criteria == 1 & nodyear < 2013) %>%
  group_by(nodyear, CI) %>%
  summarise(
    mean_aod = mean(aod),
    sd = sd(aod),
    Observations = n()
  )

ggplot(data = fig21, aes(
  x = nodyear,
  y = mean_aod,
  group = CI,
  colour = factor(CI)
)) +
  geom_point(aes(size = Observations)) + geom_line() +
  theme(
    plot.title = element_text(hjust = 0.5),
    panel.border = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black")
  ) +
  labs(
    title = "Fraction of Appeals Advanced without Documented Cause",
    x = "Notice of Disagreement Year",
    y = "Fraction of Appeals Advanced",
    color = " "
  ) +
  scale_color_discrete(labels = c("No Intervention", "Congressional Intervention")) +
  scale_x_continuous(breaks = seq(2004, 2012, 4))

ggsave(
  "./Replication Files/Figures/Figure 21.png",
  device = "png",
  width = 8,
  height = 5
)

fig22 <- survfit(Surv(adj_timeline, decided) ~ CI, data = matched_dataset_form9)

ggsurvplot(
  fig22,
  data = matched_dataset_form9,
  conf.int = TRUE,
  legend.labs = c("No Intervention", "Congressional Intervention"),
  legend.title = "",
  xlab = "Time (Days)",
  xlim = c(0, 1440),
  break.x.by = 180,
  ylab = "Probability No Decision",
  title = "Kaplan-Meier Curve - Post-Intervention Time to Decision\n",
  font.title = c(12)
)

ggsave(
  "./Replication Files/Figures/Figure 22.png",
  device = "png",
  width = 8,
  height = 5
)

################################################################################
##################### APPENDIX M: ROBUSTNESS (DISTRICT) ########################
################################################################################

# DISTRICT-LEVEL DIFFERENCES BASED ONLY ON RES = 1 

table1_res <- table1 %>%
  filter(max_res_ratio==1)

# T-TESTS FOR DIFFERENCES BETWEEN APPEALS WITHOUT/WITH CI
# APPLIES BENJAMINI HOCHBERG CORRECTION TO P-VALUES FOR MULTIPLE TESTS
runTTests <- function(data, outcome.var.names, indp.var) {
  #############################
  # data = DATAFRAME CONTAINING COLUMNS FOR split.pop.var, outcome.var, and indp.var
  # outcome.var.names = CHARACTER VECTOR OF VARIABLE NAMES USED FOR OUTCOMES
  # indp.var = STRING NAME OF VARIABLE USED FOR INDEPENDENT VARIABLE
  #############################
  # PREP LOOP
  results.df <- c()
  # SET COLUMN NAMES
  col.names <- c("outcome",
                 "control_rate",
                 "ci_rate",
                 "t_value",
                 "p_value",
                 "df",
                 "se.diff")
  for (outcome.var in outcome.var.names) {
    # T-TEST FOR CONTINUOUS VARIABLES
    possibleError <- tryCatch(
      ttest <- t.test(data[[outcome.var]] ~ data[[indp.var]]),
      error = function(e)
        e
    )
    if (inherits(possibleError, "error")) {
      tcount <- table(data[[indp.var]])
      test.row <- c(outcome.var, NA, NA, NA, NA, NA, NA)
    } else{
      tcount <- table(data[[indp.var]])
      test.row <- c(
        outcome.var,
        ttest$estimate[1],
        ttest$estimate[2],
        ttest$statistic,
        ttest$p.value,
        ttest$parameter[['df']],
        (ttest$estimate[1] - ttest$estimate[2]) / ttest$statistic
      )
    }
    # SET NAMES
    names(test.row) <- col.names
    results.df <- rbind(results.df, test.row)
  }
  results.df <-
    suppressWarnings(data.frame(results.df, stringsAsFactors = F))
  names(results.df) <- c("outcome",
                         "control_rate",
                         "ci_rate",
                         "t_value",
                         "p_value",
                         "df",
                         "se.diff")
  # CONVERT TO NUMERIC
  results.df[, c(2:ncol(results.df))] <-
    sapply(results.df[, c(2:ncol(results.df))], as.numeric)
  results.df[, 2:5] <- round(results.df[, 2:5], 2)
  results.df[, 7] <- round(results.df[, 7], 2)
  
  return(results.df)
}

outcomes = c(
  "male",
  "appellant_age_nod",
  "n_issues",
  "finhard",
  "termill",
  "advage",
  "no_aod_criteria",
  "ctyp_ps3",
  "ctyp_ps4",
  "ctyp_ps5",
  "ctyp_ps6",
  "ctyp_ps7",
  "ctyp_ps8",
  "ctyp_ps9",
  "rep_unrepresented",
  "rep_attorney",
  "rep_servorg",
  "mil",
  "female",
  "house_incumbent",
  "rep",
  "legal",
  "VA_committee",
  "ways_and_means_committee",
  "appropriations_committee",
  "budget_committee",
  "medianincome",
  "medianage",
  "prcntunemp",
  "prcntnotemploy",
  "prcnths",
  "prcntba",
  "prcntblack",
  "prcntwhite"
)

# RUN BALANCE TEST
balance.tests <- runTTests(data = table1_res,
                           outcome.var.names = outcomes,
                           indp.var = "CI")
# ADJUST FOR MULTIPLE TESTS
balance.tests$p_value_adjusted <- NA
balance.tests$p_value_adjusted <-
  p.adjust(as.numeric(balance.tests$p_value), method =
             "fdr")
balance.tests$p_value_adjusted <-
  round(balance.tests$p_value_adjusted, 2)

rownames(balance.tests) <- c(
  "Appellant is male",
  "Appellant Age at NOD (Years)",
  "Issues Per Appeal",
  "Financial Hardship",
  "Terminal Illness",
  "Advanced Age",
  "No AOD Criteria Documented",
  "WWII (9/16/40-7/25/47)",
  "Peacetime (7/26/47-6/26/50)",
  "Korean Conflict (6/27/50-1/31/55)",
  "Post-Korea (2/1/55-8/4/64)",
  "Vietnam Era (8/5/64- 5/7/75)",
  "Post-Vietnam (5/8/75-8/1/90)",
  "Persian Gulf (8/2/90-Present)",
  "Unrepresented",
  "Attorney",
  "Service Org or Agency",
  "Veteran",
  "Female",
  "Incumbent",
  "Republican",
  "Legal Background",
  "Veterans' Affairs",
  "Ways and Means",
  "Appropriations",
  "Budget",
  "Median Income",
  "Median Age",
  "Unemployment Rate (%)",
  "Population Out of the Labor Force (%)",
  "High School Education (%)",
  "College Education (%)",
  "Black Population",
  "White Population"
)
balance.tests <- balance.tests[, c(2:3, 5, 8)]
colnames(balance.tests) <- c("No Intervention",
                             "Congressional Intervention",
                             "p-value",
                             "adjusted p-value")

# CREATE TABLE 1
kbl(balance.tests, format = "latex", booktabs = T) %>%
  kable_styling(latex_options = "scale_down") %>%
  pack_rows("Appellant Demographic Characteristics", 1, 2) %>%
  pack_rows("Advancement on the Docket Criteria", 3, 6) %>%
  pack_rows("Period of Service", 7, 13) %>%
  pack_rows("Veteran Representation", 14, 17) %>%
  pack_rows("House Representative Characteristics", 18, 22) %>%
  pack_rows("House Committee Membership", 23, 26) %>%
  pack_rows("Congressional District Characteristics", 27, 34)

# TOTAL NUMBER OF UNIQUE APPELLANTS
length(unique(table1_res[table1_res$CI == 0, 'appellant_id']))
length(unique(table1_res[table1_res$CI == 1, 'appellant_id']))

# TOTAL NUMBER OF UNIQUE APPEALS
length(unique(table1_res[table1_res$CI == 1, 'appeal_id']))
length(unique(table1_res[table1_res$CI == 0, 'appeal_id']))

################################################################################
##################### APPENDIX N: MEDIATION SENSITIVITY ########################
################################################################################

matched_dataset$aod_criteria <- 1 - matched_dataset$no_aod_criteria

# MEDIATION: AOD CRITERIA DOCUMENTATION
mediator_model_a <- lm(aod_criteria ~ CI, matched_dataset)
outcome_model_a <- lm(aod ~ CI + aod_criteria, matched_dataset)
results_a <-
  mediate(
    mediator_model_a,
    outcome_model_a,
    treat = 'CI',
    mediator = 'aod_criteria' ,
    boot = TRUE,
    sims = 500
  )
summary(results_a)
plot(results_a)

sens.out_a <-
  medsens(results_a,
          rho.by = 0.1,
          effect.type = "indirect",
          sims = 100)

# MEDIATION : ISSUE DOCUMENTATION
mediator_model_b <- lm(n_issues ~ CI, data = matched_dataset)
outcome_model_b <-
  lm(n_issues_allowed ~ CI + n_issues, data = matched_dataset)
results_b <-
  mediate(
    mediator_model_b,
    outcome_model_b,
    treat = 'CI',
    mediator = 'n_issues' ,
    boot = TRUE,
    sims = 500
  )
summary(results_b)
plot(results_b)

sens.out_b <-
  medsens(results_b,
          rho.by = 0.1,
          effect.type = "indirect",
          sims = 100)

par(mfrow = c(1, 2))
plot(
  sens.out_a,
  sens.par = "rho",
  main = "AOD Criteria",
  ylim = c(-0.2, 0.2)
)
plot(
  sens.out_b,
  sens.par = "rho",
  main = "Number of Issues",
  ylim = c(-0.2, 0.2)
)

par(mfrow = c(1, 1))